#!/usr/bin/env python

import logging
import os
from config import ConfigValues

def log_cmd(log, command, message):
	log.info("{}:{}".format(command, message))

	if (command == "./waf" and message.split(':')[0] == "drift"):
		drift = message.split(':')
		#real_time = int(drift[1].strip())
		#sim_time = int(drift[2].strip())
		delta = int(drift[3].strip())
		if delta > 100:
			log.warning("Drift is more than 100 ms ({}ms). May trigger congestion event.".format(delta))
			
def init_logging(log_level=logging.INFO):
	"""
	Initialise logging with level either set on commandline or to INFO, we also use a simple format to represent the message
	"""
	logging.basicConfig(level=log_level, format=ConfigValues.LOG_FORMAT)
	
def add_logfile(log, filename, log_level=None):
	"""
	Add new log file to excisting log, the log file will inherit the same propertis as the log and log at the same level(!) if not specified
	"""
	log.debug('Adding file handler to log')
	handler = logging.FileHandler('{}/{}'.format(os.getcwd(), filename), mode='w')
	handler.setFormatter(logging.Formatter(ConfigValues.LOG_FORMAT))
	if not log_level:
		log.debug('Handler will use the same level as this log')
		handler.setLevel(log.getEffectiveLevel())
	else:
		log.debug('Setting log level to {}'.format(log_level))
		handler.setLevel(log_level)
	#Safly remove all handlers assosiated with logger and add a new one
	for handl in log.handlers:
		handl.flush()
		handl.close()
	log.handlers = []
	log.addHandler(handler)
	
def flush_logfiles(log):
	"""Flush all log files to ensure that everything is writen to disk"""
	for handle in log.handlers:
		handle.flush()